package com.lc.admin.web;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.lc.admin.base.ResponseResult;
import com.lc.admin.bean.Device;
import com.lc.admin.constants.PagerConstants;
import com.lc.admin.dto.HuaweiAuthDto;
import com.lc.admin.service.IotService;
import com.lc.admin.utils.RequestUtils;
import com.lc.admin.utils.StringUtils;
import org.apache.tomcat.util.http.RequestUtil;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.*;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.util.*;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/iot")
public class IotWeb {

    @Autowired
    RestTemplate restTemplate;

    @Autowired
    StringRedisTemplate redisTemplate;

    // 查询产品列表


    /**
     * 查询单个产品详情，也会查询到产品的物模型数据
     */
    @GetMapping("/queryProduct")
    public ResponseResult queryModel(String productId) {
        Object object = iotService.findProduct(productId);
        return ResponseResult.success(object);
    }

    /**
     * 删除设备
     */
    @DeleteMapping("/delDevice/{deviceId}")
    public ResponseResult delDevice(@PathVariable("deviceId") String deviceId) {
        iotService.delDevice(deviceId);
        return ResponseResult.success();
    }

    /**
     * 产品列表分页查询
     *
     * @param lastId：上一次查询，最后一条记录的id
     * @param limit：每页条数
     * @return
     */
    @GetMapping("/QueryProductList")
    public ResponseResult list(String lastId, @RequestParam(defaultValue = PagerConstants.PAGE_SIZE_STR) Integer limit) {
        String token = redisTemplate.opsForValue().get("huawei:auth:token");

        if (StringUtils.isEmpty(token)) {
            // 1、认证
            token = huaweiAuth();
        }
        // 2、请求接口
        StringBuffer productUrl = new StringBuffer("https://9830e5aead.st1.iotda-app.cn-north-4.myhuaweicloud.com:443/v5/iot/6dfbfac7de964fc4af3504eab3325722/products");
        boolean tag = false;
        // 如果有参数，把参数传递过去
        if (StringUtils.isNotEmpty(lastId)) {
            productUrl.append("?marker=").append(lastId);
            tag = true;
        }
        System.out.println("token=" + token);
        if (ObjectUtil.isNotEmpty(limit)) {
            if (tag) {
                productUrl.append("&limit=").append(limit);
            } else {
                productUrl.append("?limit=").append(limit);
            }
        }
        // 发送get请求，需要设置请求头（X-Auth-Token: token）,关心响应体
        HttpHeaders headers = new HttpHeaders();
        headers.set("X-Auth-Token", token);
        headers.setContentType(MediaType.APPLICATION_JSON);
        System.out.println("接口地址：" + productUrl);
        HttpEntity<String> httpEntity = new HttpEntity(headers);
        ResponseEntity<String> resp = restTemplate.exchange(productUrl.toString(), HttpMethod.GET, httpEntity, String.class);

        return ResponseResult.success(JSONObject.parseObject(resp.getBody()));
    }
//    @RequestMapping("/QueryProductList")
//    public ResponseResult list2(String lastId,
//                               @RequestParam(defaultValue = PagerConstants.PAGE_SIZE_STR) Integer limit) {
//        // 获取token，先认证
//        // 连续失败5次，封5分钟，熔断了
//        HuaweiAuthDto params = new HuaweiAuthDto();
//        String url = "https://iam.cn-north-4.myhuaweicloud.com/v3/auth/tokens";
//        ResponseEntity<String> response = restTemplate.postForEntity(url, params, String.class);
//        List<String> strings = response.getHeaders().get("X-Subject-Token");
//        String token = strings.get(0);
//
//        // 调用产品列表接口   /v5/iot/{project_id}/products
//        String productUrl = "https://9830e5aead.st1.iotda-app.cn-north-4.myhuaweicloud.com:443/v5/iot/6dfbfac7de964fc4af3504eab3325722/products";
//        HttpHeaders headers = new HttpHeaders();
//        headers.setContentType(MediaType.APPLICATION_JSON);
//        headers.set("X-Auth-Token", token);
//
//        HttpEntity<String> entity = new HttpEntity<>(headers);
//        ResponseEntity<String> response2 = restTemplate.exchange(productUrl, HttpMethod.GET, entity, String.class);
//        String body = response2.getBody();
//
//        return ResponseResult.success(JSONObject.parseObject(body));
//    }


    @PostMapping("/QueryDevice")
    public ResponseResult queryDevice(@RequestParam Map<String,Object> params){
        String token = redisTemplate.opsForValue().get("huawei:auth:token");

        if (StringUtils.isEmpty(token)) {
            // 1、认证
            token = huaweiAuth();
        }
        // 2、请求接口
        StringBuffer productUrl = new StringBuffer("https://9830e5aead.st1.iotda-app.cn-north-4.myhuaweicloud.com:443/v5/iot/6dfbfac7de964fc4af3504eab3325722/devices");

        // 处理多个参数拼接问题 ? marker=1&limit=10
        String paramsStr = RequestUtils.paramsBuild(params);
        productUrl.append(paramsStr);

        System.out.println("请求地址："+productUrl);

        // 需求：发送get请求，需要设置token，关心响应体
        HttpHeaders headers = new HttpHeaders();
        headers.set("X-Auth-Token", token);
        HttpEntity entity = new HttpEntity(headers);
        ResponseEntity<String> response = restTemplate.exchange(productUrl.toString(), HttpMethod.GET, entity, String.class);
        return ResponseResult.success(JSONObject.parseObject(response.getBody()));
    }

    /**
     * 去华为云认证
     *
     * @return
     */
//    @GetMapping("/auth")
//    public ResponseResult auth() {
//        String token = getString();
//
//        return ResponseResult.success(token);
//    }
    @NotNull
    private String huaweiAuth() {
        // 需求：发送一个post请求，需要传递json数据，还需要添加请求头；关系返回的响应体.
        HuaweiAuthDto params = new HuaweiAuthDto();
        ResponseEntity<String> response = restTemplate.postForEntity("https://iam.cn-north-4.myhuaweicloud.com/v3/auth/tokens", params, String.class);
        List<String> strings = response.getHeaders().get("X-Subject-Token");
        String token = strings.get(0);

        // 存储token到redis中
        redisTemplate.opsForValue().set("huawei:auth:token", token, 23, TimeUnit.HOURS);
        return token;
    }

    @Autowired
    IotService iotService;

    @PostMapping("/addDevice")
    public ResponseResult addDevice(@RequestBody Device device) {
        iotService.save(device);

          //  /v5/iot/{project_id}/devices
        return ResponseResult.success();
    }

    /**
     * 查询设备详情
     * @return
     */
    @PostMapping("/QueryDeviceDetail")
    public ResponseResult queryDeviceDetail(String deviceId) {
        Object response = iotService.findDeviceDetail(deviceId);
        return ResponseResult.success(response);
    }

    @PostMapping("/updateDevice")
    public ResponseResult updateDevice(@RequestBody Device device) {
        iotService.update(device);
        return ResponseResult.success();
    }

}